import { IncomingMessage, Server, ServerResponse } from "http";
import { UrlWithStringQuery } from "url";
import { PostInterface } from "./interface/app.interface";

const http = require('http');
const app: Server = http.createServer();
const url = require('url');
const queryString = require('querystring');
const fs = require('fs');
const path = require('path');
const mime = require('mime');
// model
require('./model/connect');
const user = require('./model/user');
 
app.on('request', async(req: IncomingMessage, res: ServerResponse) => {
  const Url: UrlWithStringQuery = url.parse(req.url);
  // console.log('url=>', Url);
  let method = req.method!.toLowerCase();
  let query = queryString.parse(Url.query);
  let pathname = Url.pathname;
  // console.log(query);
  let currentpath: string = ''; 
  let type: string = 'text/html;charset:utf8;'

  // 设置响应头
  res.writeHead(200, {
    'content-type': 'text/html;charset=utf8;'
  });


  // 路由
  // get -- 主要用于静态资源访问和数据获取
  if (method === 'get') {
    if (pathname == '/get') {
      // res.write(`提交成功！！您提交的信息是${query.name}---${query.pwd}`)
      res.end(`get提交成功！！您提交的信息是${query.name}---${query.pwd}`);
    }
    else if (pathname == '/' || pathname == '/index') {
      res.writeHead(200, {
        'content-type': 'application/json;charset=utf8;'
      });
      res.end(JSON.stringify({
        code: 200,
        err: "",
        msg: "成功"
      }));
    }
    else if (pathname == '/allusers') {
      let allusers = await user.find();
      res.writeHead(200, {
        'content-type': 'application/json;charset=utf8;'
      });
      res.end(JSON.stringify(allusers));
    }
    else if (pathname == '/gethtml') {
      // 获取原始字符串形式的html
      let tpl = tplObj('list');
      // res.writeHead(200, {
      //   'content-type': 'text/html;charset=utf8;'
      // });
      res.end(tpl);
    }
    else if (pathname == '/public') {
      let img = query.img;
      let publicPath = path.join(__dirname, pathname, 'image/' + img);
      fs.readFile(publicPath, (err: any, result: any) => {
        if (err !== null) {
          res.end('没有该资源');
          return;
        }
        // console.log('静态资源：', res);
        res.writeHead(200, {
          'content-type': mime.getType(publicPath)
        });
        res.end(result);
      })
    }
  }
  // post -- 主要用于动态资源访问和数据增删改查
  else if (method == 'post') {
    let postParams = '';
    let postParamsObj:PostInterface | null = null;
    if (pathname == '/post') {
      req.on('data', (data: string) => {
        postParams += data;
      });
      req.on('end', () => {
        postParamsObj = queryString.parse(postParams);
        res.end(`post提交成功！！您提交的信息是${postParamsObj!.name}---${postParamsObj!.pwd}`);
      });
    }
    else if (pathname == '/post2') {
      getPostParams(req, postParams, postParamsObj!, (postParamsObj: PostInterface) => {
        currentpath = path.join(__dirname, 'public/html/result.html');
        fs.readFile(currentpath, 'utf8', (err: any, txt: any) => {
          if (err != null) {
            res.end('404------' + pathname);
            console.log('err:', err);
            return;
          };
          type = mime.getType(currentpath);
          // console.log('type===>', mime.getType(currentpath));
          res.writeHead(200, {
            'content-type': type
          })
          res.end(txt);
        });
      });
    }
    else if (pathname == '/addUser') {// 注册用户
      getPostParams(req, postParams, postParamsObj!, async(postParamsObj: any) => {
        console.log('增加用户：', postParamsObj);
        try {
          let usr = await user.create(postParamsObj);
          res.end('用户注册成功！！' + usr.name);
        } catch (error) {
          res.end('用户注册失败！！');
          console.log('用户注册失败:', error);
        };
      });
    };
  };
});

let getPostParams = function (req: any, postParams: string, postParamsObj: any, callback: Function) {
  req.on('data', (data: string) => {
    postParams += data;
  });
  req.on('end', () => {
    postParamsObj = queryString.parse(postParams);
    console.log('post参数：', postParams, postParamsObj);
    callback(postParamsObj);
  });
};



const tplObj = function (field: string) {
  let obj: any = {
    list: `<!DOCTYPE html>
     <html lang="en">
     <head>
       <meta charset="UTF-8">
       <title>列表页面</title>
     </head>
     <body>
       <div class="container">
         <h6><a href="add.html">添加用户</a></h6>
         <!-- 表格开始 -->
         <table class="table_box">
           <!-- 第一行表头开始 -->
           <tr class="first_tr">
             <td>用户名</td>
             <td>年龄</td>
             <td>爱好</td>
             <td>邮箱</td>
             <td>操作</td>
           </tr>
           <!-- 第一行表头结束 -->
           <!-- 用户行开始 -->
           <tr class="second_tr">
             <td>张三</td>
             <td>29</td>
             <td>
               <span>抽烟</span>
               <span>喝酒</span>
               <span>打麻将</span>
             </td>
             <td class="email">222222222@souhu.com</td>
             <td>
               <a href="">删除</a>
               <a href="modify.html">修改</a>
             </td>
           </tr>
           <tr class="three_tr">
             <td>李四</td>
             <td>37</td>
             <td>
               <span>抽烟</span>
               <span>睡觉</span>
               <span>钓鱼</span>
             </td>
             <td class="email">33333332@xinlang.com</td>
             <td>
               <a href="">删除</a>
               <a href="modify.html">修改</a>
             </td>
           </tr>
           <tr class="four_tr">
             <td>王五</td>
             <td>18</td>
             <td>
               <span>睡觉</span>
               <span>吃法</span>
               
             </td>
             <td class="email">5555555@qq.com</td>
             <td>
               <a href="">删除</a>
               <a href="modify.html">修改</a>
             </td>
           </tr>
           <tr class="four_tr">
             <td>赵六</td>
             <td>54</td>
             <td>
               <span>打豆豆</span>
             </td>
             <td class="email">7777777@qq.com</td>
             <td>
               <a href="">删除</a>
               <a href="modify.html">修改</a>
             </td>
           </tr>
           <!-- 用户行结束 -->
         </table>
         <!-- 表格结束 -->
       </div>
     </body>
     </html>`,
    img: `<!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <title>图片</title>
        </head>
        <body>
          <img src=”“ alt="" width="200" height="100">
        </body>
        </html>`,
  };
  return obj[field];
 }


app.listen(3001, () => {
  console.log('server start...port is 3001');
});